<?php
require_once '../../server/utils/functions.php';
require_once '../../server/model/Machine.php';
$db = db();
$query = Array();
$parameters = Array();
if(isset($_GET["id"])&& !empty($_GET["id"])){
    $parameters["id"] = utf8_decode(htmlentities($_GET["id"]));
    $query[] = " MAC_ID=:id";
}    
if(isset($_GET["ip"])&& !empty($_GET["ip"])){
    $parameters["ip"] = utf8_decode(htmlentities($_GET["ip"]));
    $query[] = " MAC_IP_ADDR=:ip";
}    
if(isset($_GET["salle"])&& !empty($_GET["salle"])){
    $parameters["salle"] = utf8_decode(htmlentities($_GET["salle"]));
    $query[] = " SAL_ID=:salle";
}    
$where = "";
if(sizeof($query)>0){
    $where.=" WHERE";
    $i = 0;
    foreach($query as $condition){
        if($i!=0){
            $where .= " AND";
        }
        $where .= $condition;
        $i++;
    }
}
$req = $db->prepare("SELECT MAC_ID, MAC_IP_ADDR, MAC_INFOS, MAC_RAM, MAC_DISK FROM MACHINE".$where);
$req->execute($parameters);

$response = Array();
while($datas = $req->fetch()){
    $machine = new Machine(utf8_encode($datas["MAC_IP_ADDR"]), utf8_encode($datas["MAC_INFOS"]), $datas["MAC_RAM"], $datas["MAC_DISK"]);
    $machine->setId($datas["MAC_ID"]);
    $response[]= $machine;
}
if(isset($_GET["type"]) && $_GET["type"]=="xml"){
//    $xml = new SimpleXMLElement('<salles/>');
    $domtree = new DOMDocument('1.0', 'UTF-8');
    $xmlRoot = $domtree->createElement("machines");
    foreach ($response as $machine) {
        $xmlRoot->appendChild($machine->xmlSerialize($domtree));
    }
    $domtree->appendChild($xmlRoot);

    Header('Content-type: text/xml');
    echo $domtree->saveXML();
}else{
    Header('Content-type: text/json');
    echo json_encode($response);
}
$req->closeCursor();
?>
